<template>
  <div class="search-collge">
    <form action="/" @submit.prevent="onSubmit">
      <van-search
        v-model="schoolName"
        :clearable="isTrue"
        center
        :placeholder="$t('placeHolder.enterSchoolName')"
        show-action
        shape="round"
      >
        <div slot="action" @click="searchHandler">{{ $t("find") }}</div>
      </van-search>
    </form>
    <template v-if="schoolName !== ''">
      <van-cell-group
        v-for="(item, index) in schoolArray"
        :key="index"
        @click="updateCollegeInfo(item)"
      >
        <van-cell :title="item.name" clickable />
      </van-cell-group>
    </template>
    <overlay />
  </div>
</template>

<script>
import overlay from 'components/content/overlay/overlay.vue';
import { Search, Cell, CellGroup } from 'vant';
import 'vant/lib/search/style/less';
import { mapMutations } from 'vuex';

export default {
    components: {
        overlay,
        [Search.name]: Search,
        [Cell.name]: Cell,
        [CellGroup.name]: CellGroup
    },
    data () {
        return {
            schoolName: '',
            isTrue: false,
            schoolArray: undefined
        };
    },
    methods: {
    // 搜索学校
        searchHandler () {
            this.resetStatus({ state: 'showMaskLayer', status: true });
            this.$api.educationApi
                .getCollgeInfo({ schoolName: this.schoolName })
                .then(res => {
                    if (!res.size) {
                        throw new Error(this.$t('emptySearch'));
                    }
                    this.schoolArray = res.result;
                })
                .catch(error => {
                    this.$util.failToast(error.message);
                })
                .finally(() => {
                    this.resetStatus({ state: 'showMaskLayer', status: false });
                });
        },
        updateCollegeInfo (item) {
            // 将选中的学校信息传递个父组件
            this.$emit('schoolName', item.name);
            this.$router.go(-1);
        },
        onSubmit () {
            // 阻止默认事件
            return false;
        },
        ...mapMutations(['resetStatus'])
    }
};
</script>

<style scoped lang="less"></style>
